package com.oig.iframe.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.SwaggerUiConfigParameters;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class GatewaySwaggerConfig {

    /**
     * 问题只有启动的时候，才去扫一次，比gateway晚启动的，不能加入进来
     * 一般也不会有问题，如果之前已经加载过再重启微服务是没有关系的
     */
    @Bean
    @Lazy(false)
    public List<GroupedOpenApi> apis(SwaggerUiConfigParameters swaggerUiConfigParameters, RouteDefinitionLocator locator) {
        List<GroupedOpenApi> groups = new ArrayList<>();
        List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList().block();

        if (definitions==null){
            return null;
        }
        definitions.forEach(d-> log.debug("id: " + d.getId() + "  " + d.getUri().toString()));
        //如果 spring.gateway.discovery.locator.enabled=true  启用默认路由规则 ，
        // 如果自己路由配置 spring.gateway.routes 则修改 definition.getId() 排除openid即可
        definitions.stream().filter(definition -> definition.getId().startsWith("ReactiveCompositeDiscoveryClient_")).forEach(routeDefinition -> {
            String name = routeDefinition.getId().replaceAll("ReactiveCompositeDiscoveryClient_", "");
            if (name.startsWith("infra")||name.startsWith("seata")||name.startsWith("eas")) return;
            log.debug("--id--{}--name--{}",routeDefinition.getId(), name);
            //如果springdoc.swagger-ui.urls配置了，就不用swaggerUiConfigParameters了
            swaggerUiConfigParameters.addGroup(name);
            GroupedOpenApi.builder().pathsToMatch("/" + name + "/**").group(name).build();
        });
        return groups;
    }

//    // 考虑定时更新API分组 要加 EnableScheduled
//    @Scheduled(fixedDelay = 200)
//    public void refreshGroupedApi() {
//
//    }


}
